'use client';

import React, { useContext, useEffect, useState } from 'react';
import { WeatherContext } from '@/context/WeatherContext';
import { TimeContext } from '@/context/TimeContext';
import { formatUTCDate } from '@/lib/utils';
import type { WeatherData } from '@/services/api';

export default function WeatherWidget() {
  const weatherCtx = useContext(WeatherContext);
  const timeCtx = useContext(TimeContext);
  const [data, setData] = useState<WeatherData | null>(null);
  const [loading, setLoading] = useState(false);

  // 小时级别 key，减少频繁请求
  const hourKey = timeCtx
    ? timeCtx.currentTime.toISOString().split(':')[0]
    : '';

  useEffect(() => {
    if (!weatherCtx || !timeCtx) return;
    let mounted = true;
    const run = async () => {
      setLoading(true);
      const d = await weatherCtx.getWeatherForTime(timeCtx.currentTime);
      if (mounted) {
        setData(d);
        setLoading(false);
      }
    };
    run();
    return () => { mounted = false; };
  }, [weatherCtx, timeCtx, hourKey]);

  const w = data?.weather;

  const item = (label: string, value: string | number | null | undefined) => (
    <div className="flex justify-between text-xs">
      <span className="text-gray-400">{label}</span>
      <span className="text-gray-100 font-mono">{value ?? '--'}</span>
    </div>
  );

  return (
    <div className="bg-gray-900/85 backdrop-blur-md border border-gray-700 rounded-lg shadow-xl p-3 w-56 text-gray-100">
      <div className="text-sm font-semibold mb-2 flex justify-between">
        <span>天气</span>
        <span className="text-[10px] text-gray-400">UTC</span>
      </div>

      {loading && <div className="text-center text-gray-400 text-xs py-4">加载中...</div>}
      {!loading && !data && <div className="text-center text-red-400 text-xs py-4">无数据</div>}

      {!loading && data && (
        <div className="flex flex-col gap-1">
          {/* {item('记录时间', data.record_time.split('.')[0].replace('T', ' '))} */}
          {item('请求时间', formatUTCDate(timeCtx!.currentTime).split(' ')[1])}
          <hr className="border-gray-700 my-1" />
          {item('温度', (w?.mintemp ?? 'NaN') + '-' + (w?.maxtemp ?? 'NaN') + '°C')}
          {item('风向', w?.winddirect)}
          {item('风力', (w?.windspeed ?? 'NaN') + '级')}
          {item('湿度', (w?.humidity ?? 'NaN') + '%')}
          {item('降雨量', (w?.rain + 'mm'))}
          {item('空气指数', w?.air)}
          {item('空气质量级别', w?.airlevel)}
        </div>
      )}
    </div>
  );
}